package com.hourse.interceptor;

import com.hourse.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        System.out.println("经过了拦截器");
        //无论如何都放行.具体能不能操作还是在具体的操作中去判断
        //拦截器只是复制把头请求头包含token的令牌进行一个解析验证
        String header = request.getHeader("Authorization");
        if (header!=null&&!"".equals(header)){
            //如果有包含Authorization头信息，就对其进行解析
            if (header.startsWith("Bearer ")){
                //得到token
                String token=header.substring(7);
                try {
                    Claims claims = jwtUtil.parseJWT(token);
                    String roles = (String) claims.get("roles");
                    //判断是否是管理员
                    if (roles!=null||roles.equals("admin")){
                       request.setAttribute("claims_admin",token);
                    }
                    //判断是否是用户
                    if (roles!=null||roles.equals("user")){
                        request.setAttribute("claims_user",token);
                    }
                    return true;
                }catch (Exception e){
                    throw new RuntimeException("令牌不对!");

                }
            }else {
                return true;
            }
        }
        return true;
    }
}
